package com.changgou.filter;

import com.changgou.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <dl>
 * <dd>描述: ~节点业务逻辑实现</dd>
 * <dd>创建时间：  10:18 2020/3/31</dd>
 * <dd>创建人： zz</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2020/3/31      guodong       1.0        1.0 Version
 * </pre>
 * </dl>
 */
@Component
public class AuthFilter implements GlobalFilter,Ordered{

    private Logger log = LoggerFactory.getLogger(AuthFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /*
            用户认证
                1.判断请求地址是否为登录地址，如果是则放行
                2.其他地址进行鉴权----》获取请求头-----》从请求头获取token----->判空-----》校验(jwtUtil)
         */
        String urlPath = exchange.getRequest().getURI().getPath();
        //1.判断请求地址是否为登录地址，如果是则放行
        if(urlPath.contains("admin/login")){
            return chain.filter(exchange);
        }
        // 2.其他地址进行鉴权
        ServerHttpResponse response = exchange.getResponse();
        //表示无权限访问
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        String token = exchange.getRequest().getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){ //表示字符串为空
            return response.setComplete();
        }else {
            try {
                JwtUtil.parseJWT(token);
                return chain.filter(exchange);
            } catch (Exception e) {
                log.error("非法token解析失败 {}", e);
                //表示无权限访问
                return response.setComplete();
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
